package com.changge.content.api.resource;

import com.changge.common.core.domain.response.Result;
import com.changge.common.models.dto.system.resource.ModuleRoleDTO;
import com.changge.common.models.enums.system.log.OperateType;
import com.changge.common.models.vo.system.resource.ModuleRoleVO;
import com.changge.common.models.vo.system.resource.ModuleTreeVO;
import com.changge.system.facade.annotation.OperationLog;
import com.changge.system.facade.service.resource.IModuleRoleService;
import com.changge.system.facade.service.resource.IModuleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 模块角色关联控制器
 *
 * @author zhangrongkang
 * @since 2023/7/31
 */
@Tag(name = "模块角色关联控制器")
@RestController
@RequestMapping("/admin/module-role")
public class ModuleRoleController {

    @Autowired
    private IModuleService moduleService;

    @Autowired
    private IModuleRoleService moduleRoleService;

    @Operation(summary = "获取角色对应模块权限")
    @GetMapping("/listByRoleId/{id}")
    public Result<ModuleRoleVO> listByRoleId(@PathVariable Long id) {
        // 获取所有模块树形数据
        List<ModuleTreeVO> moduleTree = moduleService.getAllModuleTree();
        // 获取当前角色已有的模块权限
        List<Long> checkIds = moduleRoleService.listModuleIdByRoleId(id);

        List<String> list = new ArrayList<>();
        for (Long moduleId : checkIds) {
            list.add(String.valueOf(moduleId));
        }
        return Result.ok(new ModuleRoleVO(list, moduleTree));
    }

    @Operation(summary = "分配角色模块权限")
    @PostMapping("/save")
    @OperationLog(type = OperateType.ADD)
    public Result<Boolean> save(@Validated @RequestBody ModuleRoleDTO moduleRoleDTO) {
        return Result.ok(moduleRoleService.save(moduleRoleDTO));
    }
}
